<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" inline label-position="left" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="会员id" prop="userId">
                  <el-input v-model="queryParams.userId" placeholder="请输入会员id" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="姓名" prop="realname">
                  <el-input v-model="queryParams.realname" placeholder="请输入真实姓名" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="会员账号" prop="username">
                  <el-input v-model="queryParams.username" placeholder="请输入会员账号" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="银行卡号" prop="bankNo">
                  <el-input v-model="queryParams.bankNo" placeholder="请输入银行卡号" clearable @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="提现金额" prop="actualAmount">
                  <el-input v-model="queryParams.actualAmount" placeholder="请输入真实提现金额" clearable
                    @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="提现状态" prop="status">
                  <el-select v-model="queryParams.status" placeholder="请选择提现状态" clearable>
                    <el-option v-for="dict in stkj_withdrawal_status" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="提现时间" prop="createdTime">
                  <el-date-picker clearable v-model="queryParams.createdTime" type="date"
                    value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择提现时间" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="结束时间" prop="lastTime">
                  <el-date-picker clearable v-model="queryParams.lastTime" type="date"
                    value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="排序字段" prop="sortField">
                  <el-select v-model="queryParams.sortField" placeholder="请选择排序字段" clearable>
                    <el-option v-for="dict in sktj_sort_field" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="排序方式" prop="ascOrDesc">
                  <el-select v-model="queryParams.ascOrDesc" placeholder="请选择排序方式" clearable>
                    <el-option v-for="dict in sktj_asc_desc" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24" :offset="20">
                <el-form-item label-width="0">
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>


    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['numberWithdrawals:numberWithdrawals:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['numberWithdrawals:numberWithdrawals:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown class="mt-[1px]">
              <el-button plain type="danger">
                删除
                <el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-dropdown-item>
                  <el-dropdown-item icon="Delete" @click="handleDeleteAll()"> 全部删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown class="mt-[1px]">
              <el-button plain type="info">
                导出
                <el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item icon="Download" @click="handleExport">全部导出</el-dropdown-item>
                  <el-dropdown-item icon="Download" :disabled="multiple" @click="handleExportByIds()">
                    选择导出</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="numberWithdrawalsList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="hasData('memberInfo.id')" label="会员id" align="center" prop="memberInfo.id" width="180" />
        <el-table-column v-if="hasData('memberInfo.username')" label="会员账号" align="center" prop="memberInfo.username"
          width="120" :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('memberInfo.realname')" label="会员真实姓名" align="center" prop="memberInfo.realname"
          width="120" :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('memberInfo.phone')" label="会员手机号码" align="center" prop="memberInfo.phone"
          width="160" />
        <el-table-column label="id" align="center" prop="num" v-if="false" />
        <el-table-column v-if="hasData('actualAmount')" label="真实提现金额" align="center" prop="actualAmount" width="120"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('actualusdtAmount')" label="虚拟币提现金额" align="center" prop="actualusdtAmount"
          width="120" :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('amount')" label="提现金额" align="center" prop="amount" width="120"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('status')" label="提现状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="stkj_withdrawal_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column v-if="hasData('bankName')" label="银行名称" align="center" prop="bankName" width="180"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('bankNo')" label="银行卡号" align="center" prop="bankNo" width="180"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('approvetime')" label="批准时间" align="center" prop="approvetime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.approvetime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="hasData('createdTime')" label="提现时间" align="center" prop="createdTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="hasData('lastTime')" label="结束时间" align="center" prop="lastTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.lastTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="hasData('memberInfo.parentId')" label="会员上级id" align="center" prop="memberInfo.parentId"
          width="180" />
        <el-table-column v-if="hasData('memberInfo.parentusername')" label="会员上级账号" align="center"
          prop="memberInfo.parentusername" width="120" :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('memberInfo.userLevel')" label="会员等级" align="center"
          prop="memberInfo.userLevel" />
        <el-table-column v-if="hasData('memberInfo.status')" label="会员状态" align="center" prop="memberInfo.status">
          <template #default="scope">
            <dict-tag :options="stkj_number_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column v-if="hasData('fee')" label="率" align="center" prop="fee" />
        <el-table-column v-if="hasData('approver')" label="审核人" align="center" prop="approver" width="120"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('coin')" label="币种" align="center" prop="coin" />
        <el-table-column v-if="hasData('payType')" label="支付方式" align="center" prop="payType" width="100"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('realname') && false" label="姓名" align="center" prop="realname" />
        <el-table-column v-if="hasData('address')" label="地址" align="center" prop="address" width="180"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('orderId')" label="订单号" align="center" prop="orderId" width="120"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('memberInfo.addTime')" label="会员注册时间" align="center" prop="memberInfo.addTime"
          width="160" />
        <el-table-column v-if="hasData('memberInfo.addIp')" label="会员注册IP" align="center" prop="memberInfo.addIp"
          width="160" />
        <el-table-column v-if="hasData('memberInfo.loginIp')" label="会员登录IP" align="center" prop="memberInfo.loginIp"
          width="160" />
        <el-table-column v-if="hasData('memberInfo.mac')" label="会员MAC地址" align="center" prop="memberInfo.mac"
          width="160" />
        <el-table-column v-if="hasData('memberInfo.ip')" label="会员IP地址" align="center" prop="memberInfo.ip"
          width="160" />
        <el-table-column v-if="hasData('memberInfo.lastLoginTime')" label="最近登录时间" align="center"
          prop="memberInfo.lastLoginTime" width="160" />
        <el-table-column v-if="hasData('ip')" label="提现IP地址" align="center" prop="ip" width="160" />
        <el-table-column v-if="hasData('remark')" label="备注" align="center" prop="remark" width="180"
          :show-overflow-tooltip="true" />
        <el-table-column v-if="hasData('phone') && false" label="电话号码" align="center" prop="phone" />
        <el-table-column v-if="hasData('userId') && false" label="用户id" align="center" prop="userId" />
        <el-table-column v-if="hasData('username') && false" label="用户账号" align="center" prop="username" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['numberWithdrawals:numberWithdrawals:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['numberWithdrawals:numberWithdrawals:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改会员提现管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="numberWithdrawalsFormRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="真实提现金额" prop="actualAmount">
          <el-input v-model="form.actualAmount" placeholder="请输入真实提现金额" />
        </el-form-item>
        <el-form-item label="虚拟币提现金额" prop="actualusdtAmount">
          <el-input v-model="form.actualusdtAmount" placeholder="请输入虚拟币提现金额" />
        </el-form-item>
        <el-form-item label="提现金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入提现金额" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="批准时间" prop="approvetime">
          <el-input v-model="form.approvetime" placeholder="请输入批准时间" />
        </el-form-item>
        <el-form-item label="率" prop="fee">
          <el-input v-model="form.fee" placeholder="请输入率" />
        </el-form-item>
        <el-form-item label="审核人" prop="approver">
          <el-input v-model="form.approver" placeholder="请输入审核人" />
        </el-form-item>
        <el-form-item label="银行名称" prop="bankName">
          <el-input v-model="form.bankName" placeholder="请输入银行名称" />
        </el-form-item>
        <el-form-item label="银行卡号" prop="bankNo">
          <el-input v-model="form.bankNo" placeholder="请输入银行卡号" />
        </el-form-item>
        <el-form-item label="币种" prop="coin">
          <el-input v-model="form.coin" placeholder="请输入币种" />
        </el-form-item>
        <el-form-item label="提现时间" prop="createdTime">
          <el-date-picker clearable v-model="form.createdTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择提现时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="form.ip" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="结束时间" prop="lastTime">
          <el-input v-model="form.lastTime" placeholder="请输入结束时间" />
        </el-form-item>
        <el-form-item label="姓名" prop="realname">
          <el-input v-model="form.realname" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="订单号" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话号码" />
        </el-form-item>
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="用户账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户账号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="dict in stkj_withdrawal_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="NumberWithdrawals" lang="ts">
import { listNumberWithdrawals, getNumberWithdrawals, delNumberWithdrawals, addNumberWithdrawals, updateNumberWithdrawals, exportSelectedWithdrawals,clearNumberWithdrawals } from '@/api/numberwithdrawals/numberWithdrawals';
import { NumberWithdrawalsVO, NumberWithdrawalsQuery, NumberWithdrawalsForm } from '@/api/numberwithdrawals/numberWithdrawals/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { stkj_withdrawal_status, sktj_sort_field, sktj_asc_desc } = toRefs<any>(proxy?.useDict('stkj_withdrawal_status', 'sktj_sort_field', 'sktj_asc_desc'));
const { stkj_number_status } = toRefs<any>(proxy?.useDict('stkj_number_status'));

const numberWithdrawalsList = ref<NumberWithdrawalsVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const numberWithdrawalsFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: NumberWithdrawalsForm = {
  actualAmount: undefined,
  actualusdtAmount: undefined,
  amount: undefined,
  address: undefined,
  approvetime: undefined,
  fee: undefined,
  approver: undefined,
  bankName: undefined,
  bankNo: undefined,
  coin: undefined,
  createdTime: undefined,
  ip: undefined,
  lastTime: undefined,
  payType: undefined,
  realname: undefined,
  orderId: undefined,
  remark: undefined,
  phone: undefined,
  userId: undefined,
  username: undefined,
  status: undefined,
  memberInfo: {
    id: undefined,
    username: undefined,
    realname: undefined,
    phone: undefined,
    addTime: undefined,
    addIp: undefined,
    loginIp: undefined,
    mac: undefined,
    ip: undefined,
    parentId: undefined,
    parentusername: undefined,
    userLevel: undefined,
    status: undefined,
    lastLoginTime: undefined,
  },
}
const data = reactive<PageData<NumberWithdrawalsForm, NumberWithdrawalsQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    actualAmount: undefined,
    bankNo: undefined,
    createdTime: undefined,
    lastTime: undefined,
    realname: undefined,
    userId: undefined,
    username: undefined,
    status: undefined,
    sortField: undefined,
    ascOrDesc: undefined,
    params: {
    }
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询会员提现管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listNumberWithdrawals(queryParams.value);
  numberWithdrawalsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  numberWithdrawalsFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: NumberWithdrawalsVO[]) => {
  ids.value = selection.map(item => item.num);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加会员提现管理";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: NumberWithdrawalsVO) => {
  reset();
  const _num = row?.num || ids.value[0]
  const res = await getNumberWithdrawals(_num);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改会员提现管理";
}

/** 提交按钮 */
const submitForm = () => {
  numberWithdrawalsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      const data = {
        ...form.value,
        memberInfo: form.value.memberInfo,
      };
      if (form.value.num) {
        await updateNumberWithdrawals(data).finally(() => buttonLoading.value = false);
      } else {
        await addNumberWithdrawals(data).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}


/** 删除按钮操作 */
const handleDelete = async (row?: NumberWithdrawalsVO) => {
  const _nums = row?.num || ids.value;
  await proxy?.$modal.confirm('是否确认删除会员提现管理编号为"' + _nums + '"的数据项？').finally(() => loading.value = false);
  await delNumberWithdrawals(_nums);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('numberWithdrawals/numberWithdrawals/export', {
    ...queryParams.value
  }, `numberWithdrawals_${new Date().getTime()}.xlsx`)
}


/** 导出选中按钮操作 */
const handleExportByIds = async (row?: NumberWithdrawalsVO) => {
  try {
    const _nums = Array.isArray(row?.num) ? row?.num : Array.isArray(ids.value) ? ids.value : [];
    // 确保有数据被选中
    if (_nums.length === 0) {
      ElMessage.warning('请至少选择一项进行导出');
      return;
    }

    // 调用后端API进行导出操作，直接处理返回的Blob对象
    const response = await exportSelectedWithdrawals(_nums);

    // 由于后端直接返回了Blob，我们可以直接处理这个Blob来下载文件
    //const url = window.URL.createObjectURL(new Blob([response]));
    const url = window.URL.createObjectURL(response as unknown as Blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `numberDeposits_${new Date().getTime()}.xlsx`); // 自定义文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出选中数据时发生错误:', error);
    ElMessage.error('导出过程中发生错误，请检查网络或联系管理员');
  }
};


/**检查列中是否有数据，如果没有则隐藏该列 */
const checkColumn = (row: NumberWithdrawalsVO, column: any) => {
  return row[column.property] ? true : false;
}

/** 自定义过滤器，用于显示是否有数据 */
const hasData = (prop) => {
  return numberWithdrawalsList.value.some(item => {
    const props = prop.split('.');
    let value = item;
    for (const p of props) {
      if (value === null || value === undefined || value[p] === undefined) {
        return false;
      }
      value = value[p];
    }
    return value !== undefined && value !== null;
  });
};


/**清空表数据 */
const handleDeleteAll = async () => {
  try {
      // 确认操作
      await proxy?.$modal.confirm('确定要清空表数据吗');
      // 开始清理并加载列表
      loading.value = true;
      await clearNumberWithdrawals();
      proxy?.$modal.msgSuccess("清空数据成功");
      getList();
    } catch (error) {
      // 捕获到错误时，关闭加载状态并给出错误提示
      loading.value = false;
      console.error("操作失败", error);
      //ElMessage.error("操作失败，请稍后重试");
    } finally {
      // 确保loading状态被正确关闭
      loading.value = false;
    }
}

onMounted(() => {
  getList();
});
</script>
